﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;

namespace ImportFXData
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string strFileContent = string.Empty;
        public MainWindow()
        {
            InitializeComponent();
            
        }

        private void btnImport_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;
            if (tbFileName.Text.Length == 0)
            {
                MessageBox.Show("Please select file.");
                btnOpenFile.Focus();
                return;
            }
            if (tbProductName.Text.Length == 0)
            {
                MessageBox.Show("Please input product name.");
                tbProductName.Focus();
                return;
            }
            if (cbbProductType.SelectedIndex < 0)
            {
                MessageBox.Show("Please select product type.");
                cbbProductType.Focus();
                return;
            }

            if (strFileContent.Length > 0)
            {
                List<string> listFX = strFileContent.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();

                listFX.Remove("");
                using (FXDataCenterTableAdapters.FXDataTableAdapter adapter = new FXDataCenterTableAdapters.FXDataTableAdapter())
                {
                    adapter.DeleteQuery(tbProductName.Text, (cbbProductType.SelectedValue as ComboBoxItem).Tag.ToString());

                    int progressValue = 1;

                    lblProgress.Content = "0/" + listFX.Count.ToString();

                    foreach (string strRow in listFX)
                    {

                        string[] lstDetail = strRow.Split(',');

                        adapter.Insert(
                           tbProductName.Text,
                           (cbbProductType.SelectedValue as ComboBoxItem).Tag.ToString(),
                           DateTime.Parse(lstDetail[0] + " " + lstDetail[1]),
                           double.Parse(lstDetail[2]),
                           double.Parse(lstDetail[3]),
                           double.Parse(lstDetail[4]),
                           double.Parse(lstDetail[5]),
                           int.Parse(lstDetail[6])
                           );
                        lblProgress.Content = (progressValue++).ToString() + "/" + listFX.Count.ToString();
                    }
                }
            }

            this.Cursor = Cursors.Arrow;
            MessageBox.Show("Save successfully.");
        }

        private void btnOpenFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "CSV File (*.csv)|*.csv";
            if (openFileDialog.ShowDialog().Value)
            {
                tbFileName.Text = openFileDialog.SafeFileName;
                using (Stream fileStream = openFileDialog.OpenFile())
                {
                    strFileContent = Encoding.Default.GetString(StreamToByte(fileStream));
                }
            }
        }

        public static byte[] StreamToByte(Stream Reader)
        {
            try
            {
                MemoryStream mem = new MemoryStream(1024 * 500);
                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                int TotalByteRead = 0;

                while (true)
                {
                    bytesRead = Reader.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                        break;
                    
                    if ((Reader.Length - TotalByteRead) >= 1024)
                    {
                        mem.Write(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        mem.Write(buffer, 0, (int)(Reader.Length - TotalByteRead));
                    }

                    TotalByteRead += bytesRead;
                }

                if (mem.Length > 0)
                {
                    return mem.ToArray();
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ep)
            {
                throw ep;
            }
        }

    }
}
